/*
    解题思路：
        - 找出所有岛屿的面积，取出其中最大值
        - 找出某一岛屿面积思路：【图的遍历】
            1. 从某位置出发，向四个方向进行探寻相连的土地
            2. 每探寻到一块土地，计数加一
            3. 确保每块土地只会被探寻一次【重要】
        - 深度优先遍历
            1. 从每一个陆地出发，遍历该陆地所在的岛屿
            2. 在遍历某一岛屿的时候
                a. 从隶属于该岛屿的某一块土地出发，向四个方向递归地DFS
                b. 每次递归之后对下标进行判断，以区域的边界作为递归边界
                c. 为保证每块陆地只能访问一次，将已访问果的陆地置0
                d. 递归地返回整块岛屿的面积
*/ 
function maxAreaOfIsland(grid) {
    let res = 0;
    
    for (let row = 0; row < grid.length; row++) {
        for (let col = 0; col < grid[0].length; col++) {
            if (grid[row][col] === 1) {
                const count = dfs(row, col);
                res = Math.max(res, count);
            };
        }
    };

    function dfs(row, col) {
        if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] === 0) {
            return 0
        };

        grid[row][col] = 0;
        let count = 1;

        count += dfs(row + 1, col);
        count += dfs(row - 1, col);
        count += dfs(row, col + 1);
        count += dfs(row, col - 1);

        return count;
    }

    return res;
};





// test

const grid = [
    [0,0,1,0,0,0,0,1,0,0,0,0,0],
    [0,0,0,0,0,0,0,1,1,1,0,0,0],
    [0,1,1,0,1,0,0,0,0,0,0,0,0],
    [0,1,0,0,1,1,0,0,1,0,1,0,0],
    [0,1,0,0,1,1,0,0,1,1,1,0,0],
    [0,0,0,0,0,0,0,0,0,0,1,0,0],
    [0,0,0,0,0,0,0,1,1,1,0,0,0],
    [0,0,0,0,0,0,0,1,1,0,0,0,0]
];

const res = maxAreaOfIsland(grid);

console.log(res);